#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>

void *thread_worker1(void *args);
void *thread_worker2(void *args);

typedef struct worker_ctx_s//定义该结构体用于一次传2个参数给只有一个参数的函数
 {

	 int shared_var;//共享变量

	 pthread_mutex_t lock;//锁
 } worker_ctx_t;//这里不是该类型的结构变量，而是该结构体类型的别名

int main(int argc, char **argv)
{

	worker_ctx_t         worker_ctx;//这里才是该类型结构体变量
	worker_ctx.shared_var = 1000;
	pthread_attr_t       thread_attr;
	pthread_t            tid;

	pthread_mutex_init(&worker_ctx.lock,NULL);//初始化锁

	if( pthread_attr_init(&thread_attr) )	
       	{
	       	printf("pthread_attr_init() failure: %s\n", strerror(errno));
	       	return -1;		
       	}
	
       	if( pthread_attr_setstacksize(&thread_attr, 120*1024) )	
       	{
	       	printf("pthread_attr_setstacksize() failure: %s\n", strerror(errno));
	       	return -1;			
       	}

       	if( pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED) )	
       	{
	       	printf("pthread_attr_setdetachstate() failure: %s\n", strerror(errno));
	       	return -1;
	}

	 pthread_create(&tid,&thread_attr,thread_worker1,&worker_ctx);
	 printf("IN MAIN : Thread worker1 tid[%ld] created ok\n", tid);
	 pthread_create(&tid,&thread_attr,thread_worker2,&worker_ctx);
	 printf("IN MAIN : Thread worker2 tid[%ld] created ok\n", tid);


	 while(1)
	 {
		 printf("Main/Control thread shared_var: %d\n", worker_ctx.shared_var);
		 sleep(10);
	 
	 }

	 pthread_attr_destroy(&thread_attr);
	return 0;
}


void *thread_worker1(void *args)
{

	worker_ctx_t           *ctx = (worker_ctx_t *)args;
	if(!args)
	{
		printf("%s() get invalid arguments\n", __FUNCTION__);//一个宏定义，为该函数名称
		pthread_exit(NULL);//仅子线程退出，该函数返回值为void指针，==return NULL?
	
	}

	printf("IN WORK1 : Thread workder 1 [%ld] start running...\n", pthread_self());

	while(1)        
       	{     
		pthread_mutex_lock(&ctx->lock);
		printf("+++: %s before shared_var++: %d\n", __FUNCTION__, ctx->shared_var);
		ctx->shared_var ++;
		sleep(2);
		printf("+++: %s after sleep shared_var: %d\n", __FUNCTION__, ctx->shared_var);
		pthread_mutex_unlock(&ctx->lock);

		sleep(1);//不加延时可能会导致该进程释放锁后立刻继续执行while循环又把该锁>抢占，导致其他线程抢不到

	}
	printf("Thread workder 1 exit...\n");
	return NULL;

}

void *thread_worker2(void *args)
{
	worker_ctx_t *ctx = (worker_ctx_t *)args;
	if( !args )
	{
		printf("%s() get invalid arguments\n", __FUNCTION__);
 		pthread_exit(NULL);
	}

	printf("IN WORK2 : Thread workder 2 [%ld] start running...\n", pthread_self());
	while(1)
	{
		if(0 != pthread_mutex_trylock(&ctx->lock) )
		{
			continue;
		}

		printf("---: %s before shared_var++: %d\n", __FUNCTION__, ctx->shared_var);
		ctx->shared_var ++;
		sleep(2);
		printf("---: %s after sleep shared_var: %d\n", __FUNCTION__, ctx->shared_var);
		pthread_mutex_unlock(&ctx->lock);
		sleep(1);//不加延时可能会导致该进程释放锁后立刻继续执行while循环又把该锁抢占，导致其他线程抢不到
	}
 	printf("Thread workder 2 exit...\n");   
  	return NULL;
}
